package com.ccc.test.mq.service;

import cn.hutool.json.JSONUtil;
import com.ccc.test.common.pojo.ImgDTO;
import com.ccc.test.mq.source.MsgSource;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * 数据处理——Rabbit
 *
 * @author superC
 * @version 1.0.0
 * @date 2022/9/7
 */

@Service
public class MsgService {
    protected static final Logger logger = LoggerFactory.getLogger(MsgService.class);

    @Autowired
    private MsgSource source;


    public void sendImg(String fileName) {
        long imgStm = System.currentTimeMillis();
        // 图片
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/" + fileName);
        byte[] bytes = new byte[0];
        try {
            bytes = IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ImgDTO imgDTO = new ImgDTO();
        imgDTO.setFileName(fileName);
        imgDTO.setBytes(bytes);

        String jsonStr = JSONUtil.toJsonStr(imgDTO);
        long imgEtm = System.currentTimeMillis();
//        logger.info("组装数据耗时（毫秒）： {}", imgEtm - imgStm);

        long startTimes = System.currentTimeMillis();
        boolean result = source.sendImg().send(MessageBuilder.withPayload(jsonStr).build());
        long endTimes = System.currentTimeMillis();
        logger.info("RabbitMQ发送方法耗时（毫秒）： {}", endTimes - startTimes);
        logger.info("【业务处理】-向Rabbit发送数据，结果为{}", result);
    }

}
